from rest_framework import serializers
from .models import CustomUser, UserGroup, Role, Menu, MenuPermission, LoginHistory, UserGroupRole


class UserGroupSerializer(serializers.ModelSerializer):
    roles = serializers.SerializerMethodField()
    user_count = serializers.SerializerMethodField()

    class Meta:
        model = UserGroup
        fields = '__all__'

    def get_roles(self, obj):
        """获取用户组分配的角色"""
        group_roles = UserGroupRole.objects.filter(user_group=obj)
        return [{'id': gr.role.id, 'name': gr.role.name} for gr in group_roles]

    def get_user_count(self, obj):
        """获取用户组中的用户数量"""
        return obj.customuser_set.count()


class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = '__all__'


# PermissionSerializer 已移除，权限管理现在基于菜单权限


class MenuSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()
    
    class Meta:
        model = Menu
        fields = '__all__'
    
    def get_children(self, obj):
        children = Menu.objects.filter(parent=obj)
        return MenuSerializer(children, many=True).data


class CustomUserSerializer(serializers.ModelSerializer):
    user_groups = UserGroupSerializer(many=True, read_only=True)
    roles = RoleSerializer(many=True, read_only=True)
    
    class Meta:
        model = CustomUser
        fields = ['id', 'username', 'email', 'full_name', 'phone',
                 'avatar', 'user_groups', 'roles', 'is_active', 'is_staff', 'is_superuser',
                 'last_login', 'last_login_ip', 'login_count', 'date_joined']
        read_only_fields = ['last_login', 'last_login_ip', 'login_count', 'date_joined']


class CustomUserCreateSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    user_group_ids = serializers.ListField(child=serializers.IntegerField(), required=False)
    role_ids = serializers.ListField(child=serializers.IntegerField(), required=False)
    
    class Meta:
        model = CustomUser
        fields = ['username', 'email', 'full_name', 'phone',
                 'password', 'is_active', 'is_staff', 'user_group_ids', 'role_ids']
    
    def create(self, validated_data):
        user_group_ids = validated_data.pop('user_group_ids', [])
        role_ids = validated_data.pop('role_ids', [])
        password = validated_data.pop('password')
        
        user = CustomUser.objects.create_user(password=password, **validated_data)
        
        if user_group_ids:
            user.user_groups.set(user_group_ids)
        if role_ids:
            user.roles.set(role_ids)
            
        return user


# RolePermissionSerializer 已移除，权限管理现在基于菜单权限


class MenuPermissionSerializer(serializers.ModelSerializer):
    menu_name = serializers.CharField(source='menu.name', read_only=True)
    menu_path = serializers.CharField(source='menu.path', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True)

    class Meta:
        model = MenuPermission
        fields = '__all__'


class UserGroupRoleSerializer(serializers.ModelSerializer):
    user_group_name = serializers.CharField(source='user_group.name', read_only=True)
    role_name = serializers.CharField(source='role.name', read_only=True)

    class Meta:
        model = UserGroupRole
        fields = '__all__'


class LoginHistorySerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = LoginHistory
        fields = '__all__'
